import 'dart:async';

import 'package:avatar_glow/avatar_glow.dart';
import 'package:chatbot/liaotian.dart';
import 'package:chatbot/yanses.dart';
import 'package:chatbot/cunchu_guanli.dart';
import 'package:flutter/material.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:provider/provider.dart';
import 'package:speech_to_text/speech_to_text.dart';
import 'package:speech_to_text/speech_to_text_provider.dart';

class YuYinTiGongApp extends StatefulWidget {
  final shuoDaoXieHuiDiao yuyinDaoWenzi;
  final SpeechToText shuohua;

  final SpeechToTextProvider yuyinTiGong;

  YuYinTiGongApp(
      {required this.shuohua,
      required this.yuyinTiGong,
      required this.yuyinDaoWenzi});

  @override
  State<YuYinTiGongApp> createState() => _YuYinTiGongAppState(
      shuohua: shuohua, yuyinTiGong: yuyinTiGong, yuyinDaoWenzi: yuyinDaoWenzi);
}

class _YuYinTiGongAppState extends State<YuYinTiGongApp> {
  final SpeechToText shuohua;

  final SpeechToTextProvider yuyinTiGong;
  final shuoDaoXieHuiDiao yuyinDaoWenzi;

  _YuYinTiGongAppState(
      {required this.shuohua,
      required this.yuyinTiGong,
      required this.yuyinDaoWenzi});

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<SpeechToTextProvider>.value(
      value: yuyinTiGong,
      child: YuyinTiGongZuJian(
        speechToTextCallBack: yuyinDaoWenzi,
      ),
    );
  }
}

class YuyinTiGongZuJian extends StatefulWidget {
  final shuoDaoXieHuiDiao speechToTextCallBack;

  const YuyinTiGongZuJian({Key? key, required this.speechToTextCallBack})
      : super(key: key);

  @override
  YuyinTiGongZuJianState createState() => YuyinTiGongZuJianState();
}

class YuyinTiGongZuJianState extends State<YuyinTiGongZuJian> {
  String dangqianId = '';
  final TextEditingController wenzikongzhi = TextEditingController();
  late List<LocaleName> yuyanList;
  var focusNode = FocusNode();
  late StreamSubscription<bool> keyboardSubscription;
  bool jianPanVisible = false;

  @override
  void initState() {
    super.initState();
    yuyanList = [
      LocaleName("zh-CN", "普通话"),
      LocaleName("en-US", "英语"),
      LocaleName("fr-FR", "法语"),
      LocaleName("ko-KR", "韩语"),
      LocaleName("ja-JP", "日语"),
      LocaleName("it-IT", "意大利语"),
      LocaleName("es-ES", "西班牙语"),
      LocaleName("ru-RU", "俄语"),
      LocaleName("uk-UA", "乌克兰语"),
      LocaleName("ar-SA", "阿拉伯语"),
      LocaleName("fa-IR", "波斯语")
    ];
    var keyboardVisibilityController = KeyboardVisibilityController();
    keyboardSubscription =
        keyboardVisibilityController.onChange.listen((bool visible) {
      debugPrint('Keyboard visibility update. Is visible: $visible');
      setState(() {
        jianPanVisible = visible;
      });
    });
    dangqianId = CunChuGuanLi.dangqianYuyan(); //默认中文简体
  }

  @override
  Widget build(BuildContext context) {
    var speechProvider = Provider.of<SpeechToTextProvider>(context);
    if (speechProvider.isNotAvailable) {
      return const Center(
        child: Text('语音识别不可用, 到设置接界面打开麦克风权限.'),
      );
    }
    debugPrint("build!!!!!!!!!!");
    if (speechProvider.isListening) {
      String words = speechProvider.lastResult?.recognizedWords ?? '';
      wenzikongzhi.value = TextEditingValue(
          text: words,
          selection: TextSelection.fromPosition(TextPosition(
              affinity: TextAffinity.downstream, offset: words.length)));
    }
    return Container(
      height: jianPanVisible
          ? MediaQuery.of(context).size.height * 3 / 4
          : MediaQuery.of(context).size.height / 2,
      child: Column(crossAxisAlignment: CrossAxisAlignment.center, children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: <Widget>[
            DropdownButton(
              style: const TextStyle(
                  color: Colors.black,
                  fontSize: 15,
                  fontWeight: FontWeight.w600),
              dropdownColor: Yanse.shense,
              underline: Container(),
              onChanged: (selectedVal) => _switchLang(selectedVal),
              value: dangqianId,
              items: yuyanList
                  .map(
                    (localeName) => DropdownMenuItem(
                      value: localeName.localeId,
                      child: Text(localeName.name),
                    ),
                  )
                  .toList(),
            ),
          ],
        ),
        Container(
          height: 12,
        ),
        Container(
          alignment: Alignment.center,
          margin: const EdgeInsets.fromLTRB(16, 0, 16, 0),
          height: 120,
          width: MediaQuery.of(context).size.width - 32,
          decoration: BoxDecoration(
            color: Yanse.qianse,
            borderRadius: const BorderRadius.all(Radius.circular(12.0)),
          ),
          child: TextField(
            controller: wenzikongzhi,
            style: const TextStyle(color: Colors.black),
            keyboardType: TextInputType.text,
            focusNode: focusNode,
            maxLines: 6,
            onSubmitted: (text) {},
            textInputAction: TextInputAction.done,
            decoration: InputDecoration(
                contentPadding: const EdgeInsets.fromLTRB(8, 0, 8, 2),
                border: InputBorder.none,
                hintText:
                    speechProvider.isListening ? "正在倾听..." : "点击麦克风按钮开始说话...",
                hintStyle: const TextStyle(color: Colors.grey, fontSize: 14)),
          ),
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            InkWell(
                onTap: () {
                  speechProvider.cancel();
                  Navigator.pop(context);
                },
                child: const Text(
                  "取消",
                  style: TextStyle(color: Colors.grey, fontSize: 15),
                )),
            Stack(
              alignment: Alignment.center,
              children: [
                AvatarGlow(
                    animate: speechProvider.isListening,
                    glowColor: Yanse.jibenYanse,
                    endRadius: 76.0,
                    duration: const Duration(milliseconds: 2000),
                    repeatPauseDuration: const Duration(milliseconds: 100),
                    repeat: true,
                    child: IconButton(
                      iconSize: 56,
                      onPressed: () {
                        if (speechProvider.isListening) {
                          speechProvider.stop();
                        } else {
                          if (speechProvider.isAvailable &&
                              !speechProvider.isListening) {
                            speechProvider.listen(
                                partialResults: true, localeId: dangqianId);
                          }
                        }
                      },
                      icon: (speechProvider.isAvailable &&
                              !speechProvider.isListening)
                          ? Image.asset(
                              'assets/images/mic_normal.png',
                              width: 56,
                              height: 56,
                              fit: BoxFit.cover,
                            )
                          : Image.asset(
                              'assets/images/mic_select.png',
                              width: 56,
                              height: 56,
                              fit: BoxFit.cover,
                            ),
                    )),
                Container(
                    margin: const EdgeInsets.only(top: 64),
                    child: Text(
                      speechProvider.isListening ? "正在倾听" : "点击开始说话",
                      style: TextStyle(
                          color: Colors.grey.withOpacity(0.5), fontSize: 10),
                    ))
              ],
            ),
            InkWell(
                onTap: () {
                  if (wenzikongzhi.text.trim().isEmpty) {
                    speechProvider.cancel();
                    Navigator.pop(context);
                  } else {
                    widget.speechToTextCallBack(wenzikongzhi.text.trim());
                    speechProvider.stop();
                    Navigator.pop(context);
                  }
                },
                child: Text("发送",
                    style: TextStyle(
                        color: wenzikongzhi.text.isEmpty
                            ? Colors.grey
                            : Yanse.jibenYanse,
                        fontSize: wenzikongzhi.text.isEmpty ? 16 : 17,
                        fontWeight: wenzikongzhi.text.isEmpty
                            ? FontWeight.normal
                            : FontWeight.bold))),
          ],
        ),
        Expanded(
          child: Container(),
        )
      ]),
    );
  }

  void _switchLang(selectedVal) {
    setState(() {
      dangqianId = selectedVal;
      CunChuGuanLi.shezhiDangqianYUyan(dangqianId);
    });
    debugPrint(selectedVal);
  }
}
